package com.ygou.service.impl;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ygou.mapper.CartMapper;
import com.ygou.mapper.GoodsMapper;
import com.ygou.mapper.OrdergoodsMapper;
import com.ygou.mapper.OrdersMapper;
import com.ygou.mapper.SkusMapper;
import com.ygou.mapper.UserAddressMapper;
import com.ygou.mapper.UserRanksMapper;
import com.ygou.mapper.UsersMapper;
import com.ygou.pojo.Cart;
import com.ygou.pojo.CartExample;
import com.ygou.pojo.CountInfo;
import com.ygou.pojo.Goods;
import com.ygou.pojo.Ordergoods;
import com.ygou.pojo.OrdergoodsExample;
import com.ygou.pojo.Orders;
import com.ygou.pojo.OrdersExample;
import com.ygou.pojo.OrdersExample.Criteria;
import com.ygou.pojo.Skus;
import com.ygou.pojo.SkusExample;
import com.ygou.pojo.UserAddress;
import com.ygou.pojo.UserAddressExample;
import com.ygou.pojo.UserRanks;
import com.ygou.pojo.Users;
import com.ygou.pojo.UsersExample;
import com.ygou.service.OrdersService;
import com.ygou.utils.Tools;

@Service
public class OrdersServiceImpl implements OrdersService {
	
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrdergoodsMapper orderGoodsMapper;
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private UserAddressMapper userAddressMapper;
	@Autowired
	private UserRanksMapper userRanksMapper;
	@Autowired
	private OrdergoodsMapper ordergoodsMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private SkusMapper skusMapper;
	@Override
	public List<Orders> selectByExample(String orderNo,String createTime,Integer ispay,Integer isrefund) {
		
		
		
		OrdersExample example=new OrdersExample();
		example.setOrderByClause("createtime desc");
		Criteria c=example.createCriteria();
		
		if(orderNo!=null&&!"".equals(orderNo)){
			c.andOrdernoLike("%"+orderNo+"%");
		}
		if(createTime!=null&&!"".equals(createTime)){
			c.andCreatetimeLike("%"+createTime+"%");
		}
		if(ispay!=null&&!"".equals(ispay)){
			c.andIspayEqualTo((byte)ispay.intValue());
		}
		if(isrefund!=null&&!"".equals(isrefund)){
			c.andIsrefundEqualTo((byte)isrefund.intValue());
		}
		return ordersMapper.selectByExample(example);
	}

	@Override
	public Orders selectByPrimaryKey(Integer orderid) {
		return ordersMapper.selectByPrimaryKey(orderid);
	}

	@Override
	public boolean updateByPrimaryKey(Orders record) {
		return ordersMapper.updateByPrimaryKey(record)>0;
	}
	
	/**
	 * 统计订单数量 按条件
	 */
	@Override
	public int countByExample(Integer isrefund) {
		OrdersExample example=new OrdersExample();
		Criteria c= example.createCriteria();
		if(isrefund!=null && !"".equals(isrefund)){
			c.andIsrefundEqualTo((byte)isrefund.intValue());
		}
		return ordersMapper.countByExample(example);
	}
	
	/**
	 * 获取成交额 退款金额
	 */
	@Override
	public Double findSum(String where) {
		Double count=ordersMapper.findSum(where)==null?0:Double.parseDouble(ordersMapper.findSum(where));
		return count;
	}

	@Override
	public int addOrder(Orders order,List<Integer> cartids,Integer goodsid,Integer skuattr) {
		/**
		 * 给账单设置基础信息
		 */
		//设置订单编号
		order.setOrderno(Tools.getNowNumer());
		//获取用户信息
		UsersExample uex=new UsersExample();
		com.ygou.pojo.UsersExample.Criteria uc= uex.createCriteria();
		uc.andUseridIn(Arrays.asList(order.getUserid()));
		Users user = usersMapper.findByWhere(uex).get(0);
		order.setRealprice(new BigDecimal(order.getTotalprice().intValue()*(user.getRank().getRebate()/100.00)).setScale(2,BigDecimal.ROUND_DOWN));
		//获取当前用户的默认地址
		UserAddressExample ex=new UserAddressExample();
		com.ygou.pojo.UserAddressExample.Criteria cu= ex.createCriteria();
		cu.andUseridEqualTo(user.getUserid());
		cu.andIsdefaultEqualTo((byte)0);
		UserAddress address=userAddressMapper.selectByExample(ex).get(0);
		//设置订单收货地址
		order.setConsname(address.getUsername());
		order.setConsphone(address.getUserphone());
		order.setConsaddress(address.getAddress());
		int count=0;
		count+=ordersMapper.insert(order);
		if(cartids!=null){
			CartExample example=new CartExample();
			com.ygou.pojo.CartExample.Criteria c= example.createCriteria();
			c.andCartidIn(cartids);
			List<Cart> carts=cartMapper.selectByExample(example);
			for (Cart cart : carts) {
				Ordergoods og=new Ordergoods(0, order.getOrderid(),cart.getGoodsid(), 
						cart.getGoodscount(), cart.getGoodsprice(), cart.getGoodsnames(), 
						cart.getGoodsthums(),cart.getSkuattr(),null);
				count+=orderGoodsMapper.insert(og);
				cartMapper.deleteByPrimaryKey(cart.getCartid());
			}
		}else{
			Goods good=goodsMapper.selectByPrimaryKey(goodsid);
			Skus sku=skusMapper.selectByPrimaryKey(skuattr);
			Ordergoods og=new Ordergoods(0, order.getOrderid(),good.getGoodsid(), 
					order.getGoodcount(),sku.getPrice(), good.getGoddstitle(), 
					good.getGoodsthums(),sku.getSkuattr(),null);
			count+=orderGoodsMapper.insert(og);
		}
		
		return order.getOrderid();
	}
	/**
	 * 结算 订单
	 * @param orderid 订单编号
	 * @param userid 用户编号
	 * @return
	 */
	@Override
	public boolean balance(Integer orderid,Integer userid) {
		try {
			Orders order=ordersMapper.selectByPrimaryKey(orderid);
			Users user=usersMapper.selectByPrimaryKey(userid);
			user.setUsermoney(user.getUsermoney().subtract(order.getRealprice()));
			
			//用户所增积分
			int score=0;
			//根据订单编号获取订单商品集合
			OrdergoodsExample oex=new OrdergoodsExample();
			com.ygou.pojo.OrdergoodsExample.Criteria oc=oex.createCriteria();
			oc.andOrderidEqualTo(orderid);
			List<Ordergoods> ogs=ordergoodsMapper.selectByExample(oex);
			
			for (Ordergoods ordergoods : ogs) {
				Goods good=goodsMapper.selectByPrimaryKey(ordergoods.getGoodsid());
				//累加商品积分
				score+=good.getGoodsscore()*ordergoods.getGoodnums();
				//减少商品总库存
				good.setStock(good.getStock()-ordergoods.getGoodnums());
				
				//获取sku库存
				SkusExample sexample=new SkusExample();
				com.ygou.pojo.SkusExample.Criteria sc = sexample.createCriteria();
				sc.andGoodsidEqualTo(good.getGoodsid());
				sc.andVidEqualTo(ordergoods.getSkuattr());
				Skus sku=skusMapper.selectByExample(sexample).get(0);
				//修改sku库存
				sku.setStock(sku.getStock()-ordergoods.getGoodnums());
				skusMapper.updateByPrimaryKey(sku);
				//增加销量
				good.setSale(good.getSale()+1);
				goodsMapper.updateByPrimaryKey(good);
			}
			//增加用户积分
			user.setUserscore(user.getUserscore()+score);
			
			/**
			 * 获取等级集合 并且根据积分做等级联动
			 */
			List<UserRanks> ranks=userRanksMapper.selectByExample(null);
			for (UserRanks userRanks : ranks) {
				if(user.getUserscore()>=userRanks.getStartscore() && user.getUserscore()<=userRanks.getEndscore()){
					user.setRankid(userRanks.getRankid());
				}
			}
			usersMapper.updateByPrimaryKey(user);
			//修改订单已付款
			order.setIspay((byte)1);
			order.setPaytime(new java.util.Date());
			ordersMapper.updateByPrimaryKey(order);
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 前台获取该用户下的所有订单
	 */
	@Override
	public List<Orders> getOrdersQ(Integer userid) {
		OrdersExample example=new OrdersExample();
		Criteria c = example.createCriteria();
		c.andUseridEqualTo(userid);
		return ordersMapper.selectByExample(example);
	}

	/**
	 * 删除订单 注：此处删除订单为修改订单状态为 删除
	 * @param orderid
	 * @return
	 */
	@Override
	public boolean delOrder(Integer orderid) {
		Orders order=ordersMapper.selectByPrimaryKey(orderid);
		order.setOrderstatus((byte)-1);
		return ordersMapper.updateByPrimaryKey(order)>0;
	}

	@Override
	public Map<String, Object> count(Map<String, Object> map) {
		Map<String,Object> result=new HashMap<String,Object>();
		List<Integer> allOrderNums=ordersMapper.count(map);
		map=new HashMap<String,Object>();
		map.put("ispay",0);
		List<Integer> noPayNums=ordersMapper.count(map);
		map=new HashMap<String,Object>();
		map.put("ispay",1);
		List<Integer> yesPayNums=ordersMapper.count(map);
		map=new HashMap<String,Object>();
		map.put("issend",0);
		List<Integer> nosend=ordersMapper.count(map);
		result.put("allOrderNums", allOrderNums);
		result.put("noPayNums", noPayNums);
		result.put("yesPayNums", yesPayNums);
		result.put("nosend", nosend);
		return result;
	}
	
}
